﻿using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using Microsoft.ComponentModel;
using Microsoft.Reflection;

namespace Microsoft.Collections.ObjectModel
{
    public partial class ObservableCollectionEx<T> : INotifyObject
    {
        public void SetProperty<T1>(Expression<Func<T1>> propertyExpression, T1 value)
        {
            var propertyInfo = propertyExpression.ExtractPropertyInfo();
            if (propertyInfo != null)
                propertyInfo.SetValue(this, value);
        }

        public Boolean SetProperty<T1>(ref T1 storage, T1 value, [CallerMemberName] String propertyName = null)
        {
            if (object.Equals(storage, value)) 
                return false;
            
            storage = value;
            ((INotifyObject)this).OnPropertyChanged(propertyName);
            return true;
        }
        
        void INotifyObject.OnPropertyChanged<T1>(Expression<Func<T1>> propertyExpression)
        {
            var propertyName = propertyExpression.ExtractPropertyName();
            ((INotifyObject)this).OnPropertyChanged(propertyName);
        }
        
        void INotifyObject.OnPropertyChanged(String propertyName)
        {
            OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
        }
    }
}
